/*  header-comment
/*  file   : /Users/arida/react-hrm-h5/src/modules/growth/index
/*  author : arida
/*  date   : 2017-8-8 18:24:50
*/
import React from "react";
import Component from "../../components/SmartComponents";
import HelpModal from "../../components/HelpModal";
import PropTypes from "prop-types";
import autobind from "autobind-decorator";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";

// 业务组件
import Bonus from "./bonus";
import Avatar from "./avatar";
// import Experience from "./experience";
import Holiday from "./holiday";
import Attend from "./attend";
// import Audit from "./audit";
import CurrentJob from "./currentJob";
import Profile from "./profile";
import LeaveJobInfo from "./leaveJobInfo";
// common footer
import FooterButton from "./footerButton";
// less
import "./growth.less";

// actions
import {
  fetchUser,
  handover,
  regular,
  deleteEmployee,
  abort,
  leaveJob,
  doctor
} from "../../actions/growth/";
import { get } from "../../utils/db.js";
import { addHireTime } from "../../actions/growth/index.js";

// utils
import { set } from "../../utils/db.js";
import { setCacheData, getCacheData } from "../../utils/storeCache.js";

import {
  setTitle,
  setRight,
  alert,
  confirm,
  openLink,
  toast
} from "../../utils/dingtalk.js";

/**
 *
 * @param {string} date  xxxx-xx-xx
 * @return x月x日
 */
// function formatBithday(date) {
//   if (!date) return "";
//   return date.split("-")[1] + "月" + date.split("-")[2] + "日";
// }
// 将store注入组件的props
const mapStateToProps = state => ({ growth: state.GROWTH_USERINFO });
const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(
    {
      dispatch,
      fetchUser,
      addHireTime,
      handover,
      regular,
      deleteEmployee,
      abort,
      leaveJob,
      doctor
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Growth extends Component {
  static defaultProps = {
    growth: {
      user: {}
    }
  };
  // propTypes 验证
  static propTypes = {
    growth: PropTypes.object.isRequired,
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      fetchUser: PropTypes.func.isRequired,
      addHireTime: PropTypes.func.isRequired,
      handover: PropTypes.func.isRequired,
      regular: PropTypes.func.isRequired,
      deleteEmployee: PropTypes.func.isRequired,
      abort: PropTypes.func.isRequired,
      leaveJob: PropTypes.func.isRequired,
      doctor: PropTypes.func.isRequired
    }).isRequired
  };
  constructor(props) {
    super(props);
    setRight({
      show: false
    });
  }
  componentDidMount() {
    this.needReload();
    this.fetchProfile();
  }
  componentWillUnmount() {
    window.needReload = null;
  }
  //待刷新
  needReload() {
    const t = this;
    window.needReload = function () {
      if (window.location.href.indexOf("personalCenter") !== -1 || window.location.href.indexOf("growth") !== -1) {
        t.fetchProfile(false)
      }
    };
  }


  async fetchProfile(showLoading = true) {
    const userId = get("userId");
    //当前登录人的userId
    const currentUserId = get("currentUserId");
    const getResumeRecordInfo = "/hrmregister/mobile/resumeRecord/getResumeRecordInfo";
    //只缓存当前人的信息
    if (currentUserId === userId) {
      const cacheData = await getCacheData(getResumeRecordInfo);
      //存在缓存则读取
      if(cacheData && cacheData.oneselfFlag){//我自己
        setTitle({ title:"我的主页" })
      }

    }
    this.props.actions.fetchUser({
      userId
    },showLoading).then((res) => {
      if (res.success) {
        let title = "个人主页";
        //自己
        if (res.result && res.result.oneselfFlag) {
          title = "我的主页"
        }
        setTitle({ title })
      }
    });
  }
  @autobind
  addHireTime({ date, item }) {
    const { userId, bizUuid } = item;
    if (!userId || !bizUuid) return;
    this.props.actions
      .addHireTime({
        date,
        userId,
        bizUuid
      })
      .then(res => {
        if (res.success) {
          // 重新请求
          this.fetchProfile();
        }
      });
  }
  handleHandover(userId, employeeStatus) {
    window._rlog(`_growth_set_handOver`);

    const textMapper = {
      "2": `是否提醒员工发起转正申请`,
      "5": `是否提醒员工发起离职交接`
    };

    this.props.actions.doctor({ userId, type: "handOver" }).then(res => {
      if (res.success && res.result) {
        confirm({
          title: "",
          message: textMapper[employeeStatus],
          buttonLabels: ["取消", "确认"],
          cb: res => {
            if (res.buttonIndex === 1) {
              return this.props.actions.handover({ userId }).then(res => {
                if (res.success) {
                  toast({ text: "已发送" });
                }
              });
            }
          }
        });
      } else {
        alert({ message: "员工已发起离职交接。请在成长记录中查询" });
      }
    });
  }
  handleRegular(userId, employeeStatus) {
    window._rlog(`_growth_set_regular`);

    const textMapper = {
      "2": `是否提醒员工发起转正申请`,
      "5": `是否提醒员工发起离职交接`
    };

    this.props.actions.doctor({ userId, type: "regular" }).then(res => {
      if (res.success && res.result) {
        return this.props.actions.regular({ userId }).then(res => {
          if (res.success) {
            toast({ text: "已发送" });
          }
        });
      } else {
        alert({ message: "员工已发起转正申请。请在成长记录中查询" });
      }
    });
  }
  leaveJob({ userId, username, holidayLeft }) {
    window._rlog(`_growth_set_leave`);

    set("username", username);
    set("holidayLeft", holidayLeft);

    this.props.actions.doctor({ userId, type: "termination" }).then(res => {
      if (res.success && res.result) {
        openLink("#/leaveJob");
      } else {
        alert({ message: "该员工已经办理了离职！" });
      }
    });
  }

  delete(userId) {
    confirm({
      message: "确认离职后，会将员工从通讯录删除，员工档案将永久保存",
      buttonLabels: ["取消", "确认"],
      cb: res => {
        if (res.buttonIndex === 1) {
          this.props.actions.deleteEmployee({ userId }).then(res => {
            if (res.success) {
              toast({
                text: "已离职",
                onSuccess() {
                  window.location.reload();
                }
              });
            }
          });
        }
      }
    });
  }

  abort(userId) {
    return this.props.actions.abort({ userId }).then(res => {
      if (res.success) {
        toast({
          text: "已撤销",
          onSuccess() {
            window.location.reload();
          }
        });
      }
    });
  }

  render() {
    const userInfo = this.props.growth.user;
    if (!userInfo) {
      return null;
    }
    const baseInfo = userInfo.baseInfo;
    const empDismissionInfo = userInfo.empDismissionInfo;

    const isAdmin = userInfo.adminFlag;
    const self = userInfo.oneselfFlag; // 是否是自己看自己

    const {
      position,
      deptManager,

      employeeType,
      sex,
      name,
      uid,
      userId,
      dept,
      nickName,
      birthday,
      contractCompanyName,
      onJobCompanyName,
      jobNumber,
      confrimJoinTime
    } =
      baseInfo || {};

    const joinWorkingTime = (baseInfo && baseInfo.joinWorkingTime) || "";
    // 如果没传，默认为正式
    const employeeStatus = (baseInfo && baseInfo.employeeStatus) || "3";

    const { lastWorkDate, dismissionReason, remainAnnualDays } =
      empDismissionInfo || {};
    let workDaysContent = "";
    if (confrimJoinTime) {
      workDaysContent = userInfo.workDaysContent;
    }
    const {
      annualLeaveCount,
      // empProFileTag,
      currentMonth,
      attendanceCount,
      restCount,
      restHoursCount,
      forgetPunchCount,
      workLateCount,
      workLeaveEarlyCount,
      holidays,
      perfectFlag = true,
      approvalVO // 用来判断用户是否开启了审批，转正套件
      // 未开通提示用户开通
    } = userInfo;

    return (
      <div className="growth-container">
        <div className={`scroll-body`}>
          <Avatar
            userInfo={{
              ...baseInfo,
              position,
              onJobCompanyName,
              workDaysContent
            }}
          />
          {/* 4 离职 5 待离职 */}
          {["4", "5"].indexOf(employeeStatus) !== -1 && (
            <LeaveJobInfo
              userInfo={{
                lastWorkDate
                /* dismissionReason,
              remainAnnualDays */
              }}
            />
          )}
          <Profile
            userInfo={{
              nickName,
              sex,
              birthday: birthday,
              department: dept,
              director: deptManager,
              employeeType,
              employeeStatus,
              confrimJoinTime,
              jobNumber,
              joinWorkingTime,
              contractCompanyName,
              perfectFlag
            }}
            isSelf={self}
          />
          <Bonus
            bonusInfo={{
              logCount: userInfo.logCount,
              contractCompanyName,
              auditCount: userInfo.approveCount,
              signInCount: userInfo.signInCount,
              redPacketCount: userInfo.redPacketReward,
              attentCount: userInfo.perfectAttendanceCount,
              workHardCount: userInfo.diligentCount
            }}
            uid={uid}
            userId={userId}
            username={name}
            isSelf={self}
          />
          {employeeStatus !== "4" && (
            <div>
              <Attend
                holidayInfo={{
                  currentMonth,
                  attendanceCount,
                  restCount,
                  restHoursCount,
                  forgetPunchCount,
                  workLateCount,
                  workLeaveEarlyCount
                }}
                userId={userId}
              />
              <Holiday holidays={holidays} isSelf={self} userId={userId} />
            </div>
          )}

          <CurrentJob
            jobInfo={{
              contractCompanyName: contractCompanyName,
              onBoardCount: userInfo.entryCount,
              promotionCount: userInfo.promoteCount,
              transferCount: userInfo.transferPositionCount,
              history: userInfo.resumeRecordVPOs
            }}
            onAddHireTime={this.addHireTime}
            isAdmin={isAdmin}
            self={self}
          />
        </div>

        {/* <FooterBar isAdmin={isAdmin && self} /> */}
        <FooterButton
          isAdmin={isAdmin && !self}
          employeeStatus={employeeStatus}
          username={name}
          approvalVO={approvalVO}
          onRegularClick={this.handleRegular.bind(this, userId, employeeStatus)}
          onHandoverClick={this.handleHandover.bind(
            this,
            userId,
            employeeStatus
          )}
          leaveJob={this.leaveJob.bind(this, {
            userId,
            username: name,
            holidayLeft: annualLeaveCount
          })}
          abort={this.abort.bind(this, userId)}
          delete={this.delete.bind(this, userId)}
        />
        <HelpModal/>
      </div>
    );
  }
}
